<template>
  <div class="material">
    <!-- 筛选按钮 -->
    <div class="search-button">
      <el-button class="btn search" @click="getMaterialList"
        ><el-icon class="icon" color="#fff"> <Search /> </el-icon
        >查询</el-button
      >
      <el-button
        v-if="pageType !== 'detail'"
        class="btn save"
        @click="handleSubmit"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >确定</el-button
      >
      <el-button class="btn direction" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon
        >返回</el-button
      >
    </div>
    <!-- 筛选条件 -->
    <div class="search">
      <div class="search-item">
        <el-input
          clearable
          v-model="params.userName"
          class="search-input"
          placeholder="请输入用户名称"
        ></el-input>
      </div>
      <div class="search-item">
        <el-input
          clearable
          v-model="params.nickName"
          class="search-input"
          placeholder="请输入用户姓名"
        ></el-input>
      </div>
      <div class="search-item">
        <el-input
          clearable
          v-model="params.phonenumber"
          class="search-input"
          placeholder="请输入手机号码"
        ></el-input>
      </div>
      <div class="search-item">
        <el-select
          v-model="params.status"
          placeholder="请选择用户状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </div>
      <div class="search-item">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="创建开始日期"
          end-placeholder="创建结束日期"
        ></el-date-picker>
      </div>
    </div>
    <div class="material-container">
      <!--分类数据-->
      <div class="class-container">
        <div class="class-top">
          <el-input
            v-model="className"
            placeholder="搜索部门"
            clearable
            class="class-input"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="{ label: 'deptName', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="deptTreeRef"
            node-key="id"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </div>
      <div style="width: 85%">
        <!-- 表格数据 -->
        <el-table
          v-loading="loading"
          :data="materialList"
          border
          height="64vh"
          :header-cell-style="{ 'text-align': 'center' }"
          :header-cell-class-name="cellClass"
          ref="multipleTableRef"
          @select="handleSelectionChange"
           @select-all="handleSelectionAll"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            :selectable="checkSelectable"
          />
          <el-table-column label="用户编号" key="userId" prop="userId" />
          <el-table-column
            label="用户名称"
            align="center"
            key="userName"
            prop="userName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="用户姓名"
            align="center"
            key="nickName"
            prop="nickName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="部门"
            align="center"
            key="deptName"
            prop="fullDeptName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="手机号码"
            key="phonenumber"
            prop="phonenumber"
            width="120"
          />
          <!-- <el-table-column label="状态" align="center" key="status">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
              ></el-switch>
            </template>
          </el-table-column> -->
          <el-table-column
            label="创建人"
            align="center"
            key="createUserName"
            prop="createUserName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="160"
          >
          
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 分页 -->
    <pagination
      class="pagination"
      :total="total"
      v-model:page="params.pageNum"
      v-model:limit="params.pageSize"
      @pagination="getMaterialList"
      :page-sizes="[ 50,100,500]"
    />
  </div>
</template>

<script setup>
import { listUserAll, deptTreeSelect } from "@/api/system/user";
import { listDeptAll } from "@/api/system/dept";
const { proxy } = getCurrentInstance();
import { getDictsApi } from "@/api/dict";
import { getcategoryCateListApi } from "@/api/operation/productEstimate.js";
import useUserStore from "@/store/modules/user";
//当前用户信息
const userStore = useUserStore();
const { sys_normal_disable, sys_user_sex } = proxy.useDict(
  "sys_normal_disable",
  "sys_user_sex"
);
const emit = defineEmits([
  // 确定选中
  "submitChoose",
]);
const props = defineProps({
  // 请购单明细选中数组
  selectlist: {
    type: Array,
    default: [],
  },
});

// 搜索参数
const params = reactive({
  pageNum: 1,
  pageSize: 50,
});
const deptOptions = ref([]);
// 表格加载效果
const loading = ref(false);
// 物料列表
const materialList = ref([]);
// 总数
const total = ref(0);
// 分类名称
const className = ref("");
// 操作类型
const pageType = ref("");
// 表格选中项
const multipleSelection = ref([]);
const multipleTableRef = ref(null);
const dateRange = ref([]);
/**
 * @description: 获取物料列表
 */
const getMaterialList = async (flag) => {
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    listUserAll(proxy.addDateRange(params, dateRange.value)).then((res) => {
      if (res.code == 200) {
        if (props.selectlist.length) {
          multipleSelection.value = props.selectlist
          // materialList.value = res.rows.filter(
          //   (itemA) =>
          //     !props.selectlist.find((itemB) => itemB.userId === itemA.userId)
          // );
        } 
        handleSelectionChange(props.selectlist)
        materialList.value = res.rows;

        // materialList.value = res.rows;
        // if(props.selectlist.length) {
        //   total.value = res.total - props.selectlist.length;
        // }
        console.log('props.selectlist')
        console.log(props.selectlist)
        total.value = res.total
        loading.value = false;
        materialList.value.forEach((ele) => {
          multipleSelection.value.forEach((item, index) => {
            if (ele.userId == item.userId) {
              setTimeout(() => {
                multipleTableRef.value.toggleRowSelection(ele, true);
              }, 1000);
            }
          });
        });
      }
    });
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

// /**
//  * @description: 获取分类列表
//  */
// const getMaterialClassList = async () => {
//   let pageNum = 1,
//     pageSize = 1000;
//   const res = await getcategoryCateListApi({ pageNum, pageSize });
//   let obj = [
//     {
//       categoryId: 0,
//       categoryName: "全部",
//       parentId: null,
//       children: [],
//       id: 0,
//     },
//   ];
//   res.rows.forEach((item) => {
//     item.id = item.categoryId;
//   });
//   let treeData = proxy.handleTree(res.rows, "id");
//   obj[0].children.push(...treeData);
//   classOptions.value = obj;
// };

/**
 * @description: 通过条件过滤节点
 * @param {String} value 分类名称
 * @param {Object} data 数据源
 *
 */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/**
 * @description: 监听分类名称
 * @param {String} val 变更后分类名称
 */
watch(className, (val) => {
  proxy.$refs["deptTreeRef"].filter(val);
});

/**
 * @description: 节点单击事件
 * @param {Object} data 数据源
 */
function handleNodeClick(data) {
  if (!data.deptId) {
    params.deptId = null;
  } else {
    params.deptId = data.deptId;
  }
  getMaterialList();
}

/**
 * @description: 预览照片
 * @param {String} img 图片地址
 */
const showImg = (img) => {
  let imgArr = [];
  imgArr.push(img);
  return imgArr;
};

/**
 * @description: 返回
 */
const handleBack = () => {
  emit("update:selectionpersonnelShow", false);
};

/**
 * @description: 确定选中
 */
const handleSubmit = () => {
  console.log('multipleSelection.value')
  console.log(multipleSelection.value)
  let arr =  multipleSelection.value.filter(item=>item.userId != 1)
  emit("submitChoose",arr);
};

/**
 * @description: 隐藏表头中的全选框
 */
const cellClass = (row) => {
  if (row.columnIndex === 0) {
    return "disabledCheck";
  }
};

const checkSelectable = (row) => {
  if (row.userId == userStore.id) {
    return false;
  } else {
    return true;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  listDeptAll().then((response) => {
    
    deptOptions.value = proxy.handleTree(response.data, "deptId");
    console.log('deptOptions.value')
    console.log(deptOptions.value)
    console.log(response.data)
    // deptOptions.value = response.data;
  });
}

/**
 * @description: 处理表格选中
 */
const handleSelectionChange = (list, row) => {
  // materialList.value.forEach((ele) => {
  //   if (ele.userId == row.userId) {
  //     multipleTableRef.value.toggleRowSelection(ele, true);
  //     // multipleSelection.value.push(ele);
  //   }
  // });
  // props.selectlist.filter(item=>item.userId != 1)
  console.log(list)
    multipleSelection.value = list;
};
/**
 * @description: 表格全选
 */
 const handleSelectionAll = (list) => {
  multipleSelection.value = list;
};


/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}

onMounted(() => {
  getMaterialList();
  // getMaterialClassList();
  getDicts();
});
</script>

<style lang="scss" scoped>
.material {
  width: 100%;
  height: 100%;

  .material-container {
    display: flex;

    .class-container {
      width: 240px;
      height: 64vh;
      margin-right: 10px;
      padding-top: 30px;
      background: #ffffff;
      box-shadow: 0px 0px 10px 0px rgba(26, 43, 26, 0.1);
      border-radius: 2px;
      overflow: auto;
      .class-top {
        display: flex;
        justify-content: center;
        margin-bottom: 20px;
        .class-input {
          width: 180px;
        }
      }
    }
  }

  .pagination {
    margin: 20px auto;
  }
  :deep(.el-table) {
    .el-table__cell {
      padding: 0;
      height: 40px;
    }
    .cell.el-tooltip {
      display: flex;
      align-items: center;
    }
  }

  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
  }
  .image-slot .el-icon {
    font-size: 30px;
  }
  /* 去掉全选按钮 */
  // ::v-deep .el-table .disabledCheck .cell .el-checkbox__inner {
  //   display: none !important;
  // }
}
</style>
